import { BrowserWindow } from 'electron';
import { join } from 'node:path';
import { appTitle } from '#common/configs/build-const';
// import { platform } from '@electron-toolkit/utils';
import { getBaseConfig } from './config';
import { loadWindowUrl } from '$main/utils/window';
import { getUserDataStore } from '$main/utils/store';
import { centerDisplayPoint } from '$main/utils/screen';

let mainWindow: BrowserWindow | null = null;

function createMainWindow() {
  const centerPoint = centerDisplayPoint(350, 450);
  mainWindow = new BrowserWindow(
    getBaseConfig({
      title: appTitle,
      x: centerPoint.x,
      y: centerPoint.y,
      webPreferences: {
        preload: join(__dirname, '../preload/index.js')
      }
    })
  );
  loadWindowUrl(mainWindow)?.then(() => {});

  mainWindow.on('close', () => {
    const webContents = mainWindow!.webContents;
    const isOpenDevtools = webContents.isDevToolsOpened();
    if (isOpenDevtools) {
      webContents.closeDevTools();
    }
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  getUserDataStore()?.clear();

  return mainWindow;
}

function getMainWindow() {
  return mainWindow;
}

function showMainWindow() {
  if (!mainWindow) {
    return;
  }
  if (mainWindow.isMinimized()) {
    mainWindow.restore();
  }
  mainWindow.show();
  mainWindow.focus();
}

function destroyMainWindow() {
  if (!mainWindow) {
    return;
  }
  mainWindow?.destroy();
  mainWindow = null;
}

export { createMainWindow, getMainWindow, showMainWindow, destroyMainWindow };
